import { login, logout, getInfo } from '@/api/user'
import auth from '@/utils/auth'
import router, { resetRouter } from '@/router'
import qs from 'qs'
import axios from '@/utils/request'

const state = {
  token: auth.getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: [],
  permissionIds: [] //  权限id数组
}
const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  // SET_USERID: (state, userId) => {
  //   state.userId = userId
  // },
  //  将权限id数组存入store中
  SET_PERMISSIONIDS: (state, permissionIds) => {
    state.permissionIds = permissionIds
  },

}

const actions = {
  // user login
  login({ commit }, userInfo) {
    commit('SET_TOKEN', sessionStorage.getItem('token'))
    auth.setToken(sessionStorage.getItem('token'))

    // const { username, password } = userInfo
    // return new Promise((resolve, reject) => {
    //   login({ username: username.trim(), password: password }).then(response => {
    //     if(response.code == 200){
    //       const { data } = response
    //       commit('SET_TOKEN', data.distributionToken)
    //       setToken(data.distributionToken)
    //       resolve()
    //     }else {
    //       Message({
    //         message: response.desc,
    //         type: 'warning'
    //       })
    //       reject(response.desc)
    //     }
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {

        // const data = {}
        var data = {}

        data.roles = ['admin', 'editor']
        data.name = 'admin'
        data.avatar = 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3540845742,463471707&fm=26&gp=0.jpg'
        data.introduction = 'xxx系统'
        axios({
          method:'post',
          url:'/sysUser/selectUserRole',
          data:qs.stringify({ token:'abc123',userId: auth.getUserId()})
          // data: qs.stringify({userId: userId})
        }).then((res) => {
          data.permissionIds = [];
          var ids = res.data;
          ids.forEach(ids => {
              data.permissionIds.push(ids.modelId)
          })

          // var { roles, name, avatar, introduction, permissionIds } = data
          // if (!roles || roles.length <= 0) {
          //   reject('getInfo: roles must be a non-null array!')
          // }
          commit('SET_ROLES', data.roles)
          commit('SET_NAME', data.name)
          commit('SET_AVATAR', data.avatar)
          commit('SET_INTRODUCTION', data.introduction)
          commit('SET_PERMISSIONIDS', data.permissionIds)  //  将权限id数组存入store中
          resolve(data)
        }).catch(error => {
          reject(error.message)
        })




      // getInfo(state.token).then(response => {
      //   const { data } = response

      //   if (!data) {
      //     reject('用户认证失败, 请重新登录')
      //   }

      //   data.roles = ['admin', 'editor']
      //   data.name = 'admin'
      //   data.avatar = 'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=3540845742,463471707&fm=26&gp=0.jpg'
      //   var { roles, name, avatar, introduction } = data

      //   // roles must be a non-empty array
      //   if (!roles || roles.length <= 0) {
      //     reject('getInfo: roles must be a non-null array!')
      //   }
      //   commit('SET_ROLES', roles)
      //   commit('SET_NAME', name)
      //   commit('SET_AVATAR', avatar)
      //   commit('SET_INTRODUCTION', introduction)
      //   resolve(data)
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        commit('SET_PERMISSIONIDS', [])
        auth.removeToken()
        resetRouter()
        // dispatch('tagsView/delAllViews', null, { root: true })
        resolve()
      }).catch(error => {
        reject(error.message)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      commit('SET_PERMISSIONIDS', [])
      auth.removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async resolve => {
      const token = role + '-token'

      commit('SET_TOKEN', token)
      setToken(token)

      const { roles } = await dispatch('getInfo')

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })

      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
